<template>
  <Table
    ref="tableRef"
    :columns="columns"
    :data="loadData"
    :alert="false"
    bordered
    :showPagination="false"
    :row-key="(record: any) => record.id"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'pipelineName'">
        <a @click="handleTriggerPipelineSuccess(record.pipelineCode)">{{ record.pipelineName }}</a>
      </template>
      <template v-if="column.dataIndex === 'recentlyRunStatus'">
        <div class="running-status">
          <SvgIcon
            v-if="record.recentlyRunStatus"
            :name="pipelineStatusMap[record.recentlyRunStatus  as PipelineStatus]?.icon|| '--'"
            :style="{ marginRight: '8px', color: pipelineStatusMap[record.recentlyRunStatus  as PipelineStatus]?.color || '--'}"
            :class="{ 'svg-rotate': record.recentlyRunStatus == PipelineStatus.running }"
          />
          <span :style="{ color: pipelineStatusMap[record.recentlyRunStatus  as PipelineStatus]?.color}">{{
            pipelineStatusMap[record.recentlyRunStatus as PipelineStatus]?.text || '--'
          }}</span>
        </div>
      </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a type="link" @click="goRunPipeline(record)">运行</a>
          <a type="link" @click="goDetail(record)">详情</a>
          <a
            type="link"
            @click="goEdit(record)"
            v-auth="[
              { objectId: componentData.code, objectType: ResourceType.component, role: Role.manager },
              { objectId: appData.code, objectType: ResourceType.app, role: Role.manager },
            ]"
            >编辑</a
          >
          <a-dropdown placement="bottom">
            <SvgIcon class="iconDef" :name="'vertical'" :color="'#8ea1ba'" width="16" height="16" />
            <template #overlay>
              <a-menu>
                <a-menu-item v-for="item in dropdownList" :key="item.value" @click="item.onClick(record)">
                  <div class="dropdown-item">
                    <SvgIcon class="iconDef iconClass" :name="item.icon" :color="'#8ea1ba'" width="16" height="16" />
                    <span> {{ item.label }} </span>
                  </div>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </template>
    </template>
  </Table>
  <ViewYAMLModal ref="viewYAMLModalRef" />
  <TriggerPipelineModal ref="showActionModal" @handle-success="handleTriggerPipelineSuccess" />
</template>

<script setup lang="ts">
const router = useRouter();
import { pipelineStatusMap } from '@/settings/commonSettings';
import { PipelineStatus } from '@/enums/pipelineEnum';
import { getComponentPipelineFun } from '@/api/applicationManagement';
import { useApplicationStore } from '@/store/modules/app';
import { storeToRefs } from 'pinia';
import ViewYAMLModal from './viewYAMLModal.vue';
import TriggerPipelineModal from './triggerPipelineModal.vue';
import { ResourceType, Role } from '@/enums/pipelineEnum';
const counterStore = useApplicationStore();
const { componentData, appData } = storeToRefs(counterStore);
const props = defineProps({
  environmentUuid: {
    type: [String, Number],
    required: true,
  },
});
const viewYAMLModalRef = ref();

watch(
  () => props.environmentUuid,
  (newVal) => {
    nextTick(() => {
      newVal && tableRef.value.refresh(true);
    });
  },
  {
    immediate: true,
  },
);

watch(
  () => componentData,
  () => {
    nextTick(() => {
      tableRef.value.refresh(true);
    });
  },
  {
    immediate: true,
  },
);

const handleTriggerPipelineSuccess = (pipelineCode: string) => {
  router.push(`/system/pipelineRunning/${pipelineCode}`);
};

const viewYAML = (record: any) => {
  viewYAMLModalRef.value.onOpen(record);
};

const dropdownList = [
  {
    label: 'YAML查看',
    value: 'yaml',
    icon: 'edit2',
    onClick: (record: any) => viewYAML(record),
  },
  {
    label: '运行历史',
    value: 'history',
    icon: 'play',
    onClick: (record: any) => goRunHistory(record),
  },
];
const tableRef = ref<any>(null);
const columns = [
  { dataIndex: 'pipelineName', title: '流水线名称', align: 'center' },
  { dataIndex: 'recentlyRunStatus', title: '最近运行状态', align: 'center' },
  { dataIndex: 'recentlyRunStage', title: '最近任务', align: 'center' },
  { dataIndex: 'triggerInfo', title: '触发信息', align: 'center' },
  { dataIndex: 'recentlyBuildNumber', title: '最新构建号', align: 'center' },
  { dataIndex: 'totalTaskCount', title: '步骤总数', align: 'center' },
  { dataIndex: 'executedCount', title: '已执行次数', align: 'center' },
  { dataIndex: 'recentlyRunStartTime', title: '最近运行开始时间', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

const loadData = async () => {
  if (!props.environmentUuid) return;
  return await getComponentPipelineFun({
    componentLabel: componentData.value.label,
    environmentUuid: props.environmentUuid,
  }).then((res) => {
    const data = [res];
    return data;
  });
};

const showActionModal = ref<any>();

const goDetail = (record: Pipeline.BaseInfo) => {
  router.push(`/system/pipelineDetail/info/${record.pipelineCode}`);
};

//运行流水线
const goRunPipeline = (record: Pipeline.BaseInfo) => {
  showActionModal.value.showModal(record);
};

const goEdit = (record: Pipeline.BaseInfo) => {
  router.push(`/system/pipelineConfig/${record.pipelineCode}`);
};

const goRunHistory = (record: Pipeline.BaseInfo) => {
  router.push(`/system/pipelineRunning/${record.pipelineCode}/runHistory`);
};
</script>

<style scoped lang="less">
.running-status {
  display: flex;
  justify-content: center;
  align-items: center;
}
.table-operation {
  width: 150px;
  display: flex;
  align-items: center;
}

.dropdown-item {
  display: flex;
  align-items: center;
  .iconDef {
    margin-right: 8px;
  }
}

.record-form {
  margin-bottom: 24px;
}

:deep(.ant-dropdown-menu-item:hover, .ant-dropdown-menu-submenu-title:hover) {
  background-color: rgba(37, 144, 255, 0.1);
}
</style>
